// AvatarCtrl.cpp : implementation file
//

#include "stdafx.h"
#include "AvatarCtrl.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CAvatarCtrl

CAvatarCtrl::CAvatarCtrl()
{
}

CAvatarCtrl::~CAvatarCtrl()
{
}


BEGIN_MESSAGE_MAP(CAvatarCtrl, CStatic)
	//{{AFX_MSG_MAP(CAvatarCtrl)
	ON_WM_TIMER()
	ON_WM_PAINT()
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CAvatarCtrl message handlers

BOOL CAvatarCtrl::SetGifFile(LPCTSTR pszFileName)
{
	if(!m_gif.Load(pszFileName)) return FALSE;
	m_nCurFrame=-1;
	OnTimer(100);
	return TRUE;
}

void CAvatarCtrl::OnTimer(UINT nIDEvent) 
{
	KillTimer(nIDEvent);
	m_nCurFrame++;
	if(m_nCurFrame>=(int)m_gif.m_nFrameCount) m_nCurFrame=0;
	CGifFrame *pFrame=m_gif.GetFrame(m_nCurFrame);
	DrawFrame(pFrame);
	int nDelay=pFrame->m_nDelayTime;
	if(nDelay==0) nDelay=10;
	SetTimer(100,nDelay*10,NULL);
}

void CAvatarCtrl::DrawFrame(CGifFrame *pFrame,CDC *pDC)
{
	BOOL bFreeDC=pDC==NULL;
	if(bFreeDC)
	{
		pDC=GetDC();
	}
	CDC memdc;
	CBitmap bmp;
	memdc.CreateCompatibleDC(pDC);
	bmp.CreateCompatibleBitmap(pDC,m_gif.m_nWidth,m_gif.m_nHeight);
	CBitmap *pOldBmp=memdc.SelectObject(&bmp);
	memdc.FillSolidRect(0,0,m_gif.m_nWidth,m_gif.m_nHeight,RGB(192,192,192));
	pFrame->ShowImage(memdc.m_hDC,0,0,0,0,m_gif.m_nWidth,m_gif.m_nHeight);
	pDC->BitBlt(0,0,m_gif.m_nWidth,m_gif.m_nHeight,&memdc,0,0,SRCCOPY);
	memdc.SelectObject(pOldBmp);
	memdc.DeleteDC();
	if(bFreeDC)
	{
		ReleaseDC(pDC);
	}
}

void CAvatarCtrl::OnPaint() 
{
	CPaintDC dc(this); // device context for painting
	
	// TODO: Add your message handler code here
	if(m_gif.m_nFrameCount)
	{
		ASSERT((int)m_gif.m_nFrameCount>m_nCurFrame);
		CGifFrame *pFrame=m_gif.GetFrame(m_nCurFrame);
		DrawFrame(pFrame,&dc);
	}
	// Do not call CStatic::OnPaint() for painting messages
}
